package com.yangfan.juc.atomic;

/**
 * @description: 5个线程一起 争抢锁
 * @author: yangfan
 * @date: Created in 2020/3/20 0020 15:40
 * @modified By:
 */
public class CompareAndSetLockTest {

    private static CompareAndSetLock lock = new CompareAndSetLock();


    public static void main(String[] args) {


        for(int i=0 ; i<5 ; i++){
            new Thread(){
                @Override
                public void run() {
                    try {
                        task();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }

    }



    private static void task() throws InterruptedException {
        try {
            lock.tryLock();
            System.out.println(Thread.currentThread().getName() + ":" + "抢到锁了！");
            Thread.sleep(1000000);//假设是一个特别耗时的一个工作
        } catch (GetLockException e) {//不会没有抢到锁的异常
            //如果没有抢到锁可以过一会在试一试重新抢一次。
            e.printStackTrace();
        } finally {
            lock.unLock();
        }
    }




}
